<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

use builder\helper\App;
use builder\helper\Url;
use yii\helpers\Json;

/* ----------- 树组件JavaScript ----------- */
/** @var \yii\web\View $this 当前视图实例 */
/** @var \builder\tree\TreeBuilder $context 当前树组件构建器实例 */
/** @var boolean $showCheckbox 是否显示复选框 */
/** @var boolean $accordion 是否开启手风琴模式 */
/** @var boolean $onlyIconControl 是否仅允许节点左侧图标控制展开伸缩 */
/** @var boolean $isJump 是否允许点击节点时弹出新窗口跳转。若为 true，则需在对应的 data 中设定 href 属性（url 格式） */
/** @var boolean $showLine 是否开启节点连接线。若设为 false，则节点左侧出现三角图标。 */
/** @var array $customName 自定义 data 数据源中常用的字段名称 */
/** @var boolean $autoRequest 是否自动发起数据请求 */
/** @var string $ajaxRoute AJAX请求路由 */
/** @var array $defaultText 自定义一些默认文本 */
/** @var array $operationItemRaw 自定义操作项(未分组) */
/* @var array $extraJs 额外的JS脚本 */

$context = $this->context;
?>
<script>
    ~function (global, top) { "use strict";
        global.ym2App.controller("ym2.ctrl.<?= $context->id ?>", [
            "$scope",
            "$http",
            "layui",
            "ymSpinner",
            "ym2",
            "swal",
            "$timeout",
            function ($scope, $http, layui, ymSpinner, ym2, swal, $timeout) {
                var topToastr = top.toastr;
                var topLayer = top.layui.layer;
                var topJquery = top.jQuery;
                var topSwal = top.swal;
                var TREE = layui.tree;
                var UTIL = layui.util;
                var TREE_ID = "<?= $context->id ?>";
                var AUTO_REQUEST = <?= $autoRequest ?>;
                var treeData = [];

                //渲染
                var TreeOption = {
                    id: TREE_ID,
                    elem: "#ym2_builder_" + TREE_ID,
                    data: treeData,
                    showCheckbox: Boolean(<?= $showCheckbox ?>),
                    accordion: Boolean(<?= $accordion ?>),
                    onlyIconControl: Boolean(<?= $onlyIconControl ?>),
                    isJump: Boolean(<?= $isJump ?>),
                    showLine: Boolean(<?= $showLine ?>),
                    text: <?= Json::encode($defaultText) ?>,
                };
                <?php if (!empty($customName)): ?>

                TreeOption.customName = <?= Json::encode($customName) ?>;
                <?php endif; ?>

                TREE.render(TreeOption);
                //请求数据
                var request_data = function () {
                    // show loading
                    var flag = ymSpinner.show();
                    $http.get("<?= $ajaxRoute ?>").then(function (result) {
                        ymSpinner.hide(flag);

                        var data = result.data;
                        if (data.code === <?= App::params('http.res.success') ?>) {
                            //200
                            treeData = data.data || [];
                            TREE.reload(TREE_ID, {
                                data: treeData,
                            });
                        } else if (data.code === <?= App::params('http.res.failure') ?>) {
                            //500
                            topToastr.error(data.msg);
                        } else if (data.code === <?= App::params('http.res.unauthorized') ?>) {
                            // 401
                            ym2.swal.timer(
                                topSwal,
                                data.msg,
                                "自动跳转; <a href='<?= Url::to(App::params('admin.route.login'), '') ?>' target='_top'>立即跳转<a/>",
                                function () {
                                    top.open("<?= Url::to(App::params('admin.route.login'), '') ?>", "_self");
                                },
                                3000
                            );
                        } else {
                            topToastr.error(data.msg);
                        }

                    }, function (error) {
                        ymSpinner.hide(flag);
                        topToastr.error(error.data || "系统错误, 发起请求失败!");
                        global.console.error(error);
                    });
                };
                //自动重载和挂载重载方法
                if (AUTO_REQUEST) {
                    request_data();
                } else {
                    global.ym2BehaviorReqExport[TREE_ID] = function () {
                        request_data();
                    };
                }
                //全选/反选
                var recursive_checked = function (data) {
                    data = data || treeData;
                    data.forEach(function (value, index, array) {
                        if (ym2.typeOf(value.children) === 'array' && value.children.length) {
                            recursive_checked(value.children);
                        } else {
                            value.checked = initCheckedSate;
                        }
                    });
                };
                var initCheckedSate = true;
                $scope.toggleAll = function () {
                    recursive_checked();
                    initCheckedSate = !initCheckedSate;

                    TREE.reload(TREE_ID, {
                        data: treeData,
                    });
                };
                //展开/折叠
                var recursive_spread = function (data) {
                    data = data || treeData;
                    data.forEach(function (value, index, array) {
                        value.spread = !value.spread;
                        if (value.children) {
                            recursive_spread(value.children);
                        }
                    });
                };
                $scope.toggleSpread = function () {
                    recursive_spread();

                    TREE.reload(TREE_ID, {
                        data: treeData,
                    });
                };
                //自定义工具事件
                var format_checked_data_called = function (currentData, formattedCheckedData) {
                    currentData.forEach(function (value, index, array) {
                        if (typeof value === "object" && value !== null) {
                            var children = value.children;
                            delete value.children;
                            formattedCheckedData.push(value);
                            if (children && topJquery.isArray(children)) {
                                format_checked_data_called(children, formattedCheckedData);
                            }
                        }
                    });
                };
                UTIL.event('lay-on', {
                    <?php foreach ($operationItemRaw as $key => $item): ?>

                    "<?= $item['options']['__event_id'] ?>": function() {
                        //工具操作配置项
                        var configs = <?= Json::encode($item) ?>;
                        //获取选中节点的数据
                        var checkedData = TREE.getChecked(TREE_ID) || [];
                        //clone数据
                        var cloneCheckedData = ym2.deepCopy(checkedData);
                        //格式化数据
                        var formattedCheckedData = [];
                        format_checked_data_called(cloneCheckedData, formattedCheckedData);
                        //类型分发
                        custom_operation_event_dispatch(configs, formattedCheckedData);
                    },
                    <?php endforeach; ?>

                });
                /**
                 * 自定义工具操作 - 类型分发
                 * @param configs 工具项配置
                 * @param checkedData 选中数据
                 */
                function custom_operation_event_dispatch(configs, checkedData) {
                    switch (configs.options.type) {
                        case "page": // 单页
                            dispatch_page_event(configs, checkedData);
                            break;
                        case "modal": // 模态框
                            dispatch_modal_event(configs, checkedData);
                            break;
                        case "ajax": // AJAX
                            dispatch_ajax_event(configs, checkedData);
                            break;
                    }
                }
                /**
                 * 自定义工具操作 - 单页
                 * @param configs 工具项配置
                 * @param checkedData 选中数据
                 */
                function dispatch_page_event(configs, checkedData) {
                    // Request Params
                    var requestParams = configs.options.params || [];
                    // URL
                    var url = configs.options.route;
                    // target
                    var target = configs.options.target;
                    // 是否必须选择checkbox
                    var mustSelectCheckbox = !!configs.options.__mustSelectCheckbox;
                    // 处理后的请求参数
                    var params;

                    // 请参数不为空
                    if (ym2.keys(requestParams).length) {
                        if (mustSelectCheckbox) {
                            // 选中的数据
                            if (!checkedData.length) {
                                topToastr.warning("请选择数据列!");
                                return;
                            }

                            // URL参数
                            params = ym2.fillParamsMany(requestParams || [], checkedData);
                        } else {
                            params = requestParams;
                        }

                        // href
                        url = ym2.addUrlQueryParam(url, params);
                    }

                    // 打开
                    global.open(url, target);
                }
                /**
                 * 自定义工具操作 - 模态框
                 * @param configs 工具项配置
                 * @param checkedData 选中数据
                 */
                function dispatch_modal_event(configs, checkedData) {
                    // Request Params
                    var requestParams = configs.options.params || [];
                    // URL
                    var url = configs.options.route;
                    // modal width
                    var width = configs.options.width;
                    // modal height
                    var height = configs.options.height;
                    // modal footer close btn
                    var footerCloseBtn = configs.options.closeBtn;
                    // layer screen obj
                    var layerScreenObj = ym2.layerScreenOptions(width);
                    // 是否必须选择checkbox
                    var mustSelectCheckbox = !!configs.options.__mustSelectCheckbox;
                    // 处理后的请求参数
                    var params;

                    // 请参数不为空
                    if (ym2.keys(requestParams).length) {
                        if (mustSelectCheckbox) {
                            // 选中的数据,二维JSON
                            if (!checkedData.length) {
                                topToastr.warning("请选择数据列!");
                                return;
                            }

                            // URL参数
                            params = ym2.fillParamsMany(requestParams || [], checkedData);
                        } else {
                            params = requestParams;
                        }

                        // href
                        url = ym2.addUrlQueryParam(url, params);
                    }

                    // layer动态唯一索引
                    var activeIndex = topLayer.index;
                    // iframe 模态框
                    var layerCf = {
                        type: 2, // iframe
                        //skin: 'layui-layer-win10',
                        area: [layerScreenObj.width, height],
                        title: configs.title,
                        shade: 0.3, // 遮罩透明度
                        shadeClose: false, // 点击遮罩区域，关闭弹层
                        //closeBtn: layerScreenObj.closeBtn,
                        maxmin: true, // 允许全屏最小化
                        anim: 0, // 0-6 的动画形式，-1 不开启
                        scrollbar: false, // 打开弹层时，是否允许浏览器出现滚动条。
                        content: url,
                        success: function(layero, index, that){
                            // 弹层的最外层元素的 jQuery 对象
                            //console.log(layero);
                            // 弹层的索引值
                            //console.log(index);
                            // 弹层内部原型链中的 this --- 2.8+
                            //console.log(that);
                            // 获取iframe的窗口对象, 添加来源追踪
                            var iframeWin = top[layero.find("iframe")[0]["name"]];
                            iframeWin.__REFERER_WIN_NAME = global.name;
                            //键盘事件关闭
                            topJquery(".ym2_kc_" + activeIndex).focus().on("keydown", function (e) {
                                // 空格和回车键
                                if (e.keyCode === 13 || e.keyCode === 32) {
                                    topJquery(this).trigger("click");
                                }
                            });
                        },
                    };
                    if (footerCloseBtn) {
                        layerCf.btn = ['<span class="ym2_keydown_close ym2_kc_' + activeIndex + '" tabindex="0">关闭</span>'];
                    }

                    topLayer.open(layerCf);
                }
                /**
                 * 自定义工具操作 - AJAX
                 * @param configs 工具项配置
                 * @param checkedData 选中数据
                 */
                function dispatch_ajax_event(configs, checkedData) {
                    // Request Params
                    var requestParams = configs.options.params || [];
                    // URL参数
                    var params = {};
                    // 是否必须选择checkbox
                    var mustSelectCheckbox = !!configs.options.__mustSelectCheckbox;

                    // 请参数不为空
                    if (ym2.keys(requestParams).length) {
                        if (mustSelectCheckbox) {
                            // 选中的数据,二维JSON
                            if (!checkedData.length) {
                                topToastr.warning("请选择数据列!");
                                return;
                            }

                            // URL参数
                            params = ym2.fillParamsMany(requestParams || [], checkedData);
                        } else {
                            params = requestParams;
                        }
                    }

                    ym2.swal.question(topSwal, configs.options.questionTitle, configs.options.questionDescription, function (result) {
                        /* Read more about isConfirmed, isDenied below */
                        if (result.isConfirmed) {
                            // 发起ajax
                            custom_operation_ajax_request(configs, params, checkedData);
                        }
                    });
                }
                /**
                 * 自定义工具操作 - AJAX请求
                 * @param configs 工具项配置
                 * @param params 请求参数
                 * @param checkedData 选中数据
                 */
                function custom_operation_ajax_request(configs, params, checkedData) {
                    // URL
                    var url = configs.options.route;
                    // HTTP method
                    var method = configs.options.method;
                    //是否关闭当前窗口层
                    var closeModal = configs.options.closeModal || false;
                    //是否提交后重载tree组件,默认false
                    var submittedReload = configs.options.submittedReload || false;
                    //提交后的回调
                    var submittedCalls = configs.options.submittedCalls || [];

                    var instance;
                    if (method.toUpperCase() === "GET") {
                        var u = ym2.addUrlQueryParam(url, params);
                        instance = $http.get(u);
                    } else if (method.toUpperCase() === "POST") {
                        instance = $http.post(url, params);
                    }

                    // show loading
                    var flag = ymSpinner.show();
                    instance.then(function (result) {
                        ymSpinner.hide(flag);

                        var data = result.data;
                        if (data.code === <?= App::params('http.res.success') ?>) {
                            ym2.swal.ok(topSwal, data.msg);
                            //重载树组件
                            if (!closeModal && submittedReload) {
                                $timeout(function () {
                                    request_data();
                                }, 40);
                            }
                            //关闭窗口
                            if (closeModal) {
                                // 自动关闭弹窗
                                try {
                                    var layerIndex = topLayer.getFrameIndex(global.name);
                                    topLayer.close(layerIndex);
                                } catch (e) {console.warn('Failed to close the modal frame.');}
                            }
                            //提交后回调
                            Object.keys(submittedCalls).forEach(function (key) {
                                var callbackMethod = submittedCalls[key] || [];
                                var callbackMethodDataType = ym2.typeOf(callbackMethod);
                                if (['object', 'array'].indexOf(callbackMethodDataType) < 0) {
                                    callbackMethod = new Array(callbackMethod);
                                }

                                if (key === "self") {//self
                                    var selfCbkExport = global.ym2CbkExport || {};
                                    if (!callbackMethod.length) {
                                        // 回调所有
                                        Object.keys(selfCbkExport).forEach(function (key) {
                                            /* $scope 当前表单域 */
                                            selfCbkExport[key].call();
                                        });
                                    } else {
                                        // 指定回调
                                        Object.keys(selfCbkExport).forEach(function (key) {
                                            if (lodash.indexOf(callbackMethod, key) !== -1) {
                                                /* $scope 当前表单域 */
                                                selfCbkExport[key].call();
                                            }
                                        });
                                    }
                                } else {//parent.parent.*
                                    if (global !== global.parent) {
                                        var keysMap = key.split('.');
                                        var currentWin = global;
                                        var refererWinName = currentWin.__REFERER_WIN_NAME;
                                        var parentWin;
                                        for (var i = 0; i < keysMap.length; i++) {
                                            parentWin = refererWinName ? top[refererWinName] : currentWin.parent;
                                            refererWinName = parentWin.__REFERER_WIN_NAME;
                                            currentWin = parentWin;
                                        }

                                        var parentCbkExport = parentWin.ym2CbkExport || {};
                                        if (!callbackMethod.length) {
                                            // 回调所有
                                            Object.keys(parentCbkExport).forEach(function (key) {
                                                /* $scope 当前表单域 */
                                                parentCbkExport[key].call();
                                            });
                                        } else {
                                            // 指定回调
                                            Object.keys(parentCbkExport).forEach(function (key) {
                                                if (lodash.indexOf(callbackMethod, key) !== -1) {
                                                    /* $scope 当前表单域 */
                                                    parentCbkExport[key].call();
                                                }
                                            });
                                        }
                                    }
                                }

                            });
                        } else if (data.code === <?= App::params('http.res.failure') ?>) {
                            ym2.swal.fail(topSwal, data.msg);
                        } else if (data.code === <?= App::params('http.res.unauthorized') ?>) {
                            // 授权失效, 去登录
                            ym2.swal.timer(
                                topSwal,
                                data.msg,
                                "自动跳转; <a href='<?= Url::to(App::params('admin.route.login'), '') ?>' target='_top'>立即跳转<a/>",
                                function () {
                                    top.open("<?= Url::to(App::params('admin.route.login'), '') ?>", "_self");
                                },
                                3000
                            );
                        } else {
                            ym2.swal.fail(topSwal, data.msg);
                        }
                    }, function (error) {
                        ymSpinner.hide(flag);
                        ym2.swal.fail(topSwal, error.data || "系统错误, 发起请求失败!");
                        global.console.error(error);
                    });
                }

                //额外的JS脚本
                <?= !empty($extraJs) ? implode("\n", $extraJs) : '' ?>

                // 暴露给window，用于回调刷新
                global.ym2CbkExport[TREE_ID] = request_data;

            },
        ]);
    }(window, top);
</script>
